﻿using System;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using App_Code;
using DM4;

public partial class DefaultPage : Page
{
    // ReSharper disable InconsistentNaming
    protected void Page_Load(object sender, EventArgs e)
    // ReSharper restore InconsistentNaming
    {
        if (!IsPostBack) //first page load
        {
            if (Request.Params["LoginSuccess"] != "true")
                TryToLoginWithCookies();

            //CommonProc.GetGroupList(CommonVars.Ui.Id);
            GridView1.DataSource = CommonVars.GroupInfods.Tables["tbl"];
            GridView1.DataBind();
        }
        InitPage();
    }

    protected void NextButtonClick(object sender, EventArgs e)
    {
        //pnlMain2.Visible = pnlMain1.Visible;
        //pnlMain1.Visible = !pnlMain2.Visible;
    }


    private void TryToLoginWithCookies()
    {
        HttpCookie cEndpointAddress = Request.Cookies[CommonVars.EndpointAddress];
        if (cEndpointAddress == null || string.IsNullOrEmpty(cEndpointAddress.ToString()))
            Response.Redirect(CommonVars.LoginPageRelUrl, true);
        else
        {
            if (CommonProc.CreateServerChannel(cEndpointAddress.Value))
            {
                HttpCookie cLogin = Request.Cookies[CommonVars.Login];
                if (cLogin == null
                    || string.IsNullOrEmpty(cLogin.Value))
                    Response.Redirect(CommonVars.LoginPageRelUrl, true);

                HttpCookie cPass = Request.Cookies[CommonVars.Password];
                if (cPass == null || string.IsNullOrEmpty(cPass.Value))
                    Response.Redirect(CommonVars.LoginPageRelUrl, true);

                if (cPass == null
                    || cLogin == null
                    || !CommonProc.ServerLogin(cLogin.Value, cPass.Value))
                    Response.Redirect(CommonVars.LoginPageRelUrl, true);
            }
            else
                Response.Redirect(CommonVars.LoginPageRelUrl, true);
        }
    }
    protected void GvSelectedIndexChanged(Object sender, EventArgs e)
    {

        // Get the currently selected row using the SelectedRow property.
        GridViewRow row = GridView1.SelectedRow;

        string name = row.Cells[2].Text;
        Label2.Text = name;

        //ClientScript.RegisterStartupScript(this.GetType(), "myScript", "<script type=\"text/javascript\">function test() {document.getElementById('ButtonBtn').value = '" + name + @"';}</script>");
        // Display the company name from the selected row.
        // In this example, the third column (index 2) contains
        // the company name.
        //Message.Text = "You selected " + row.Cells[2].Text + ".";

    }
    private void InitPage()
    {
        Page.Title = CommonVars.DefaultPageTitle;

        //if (CommonVars.Ui == null || CommonVars.Ui.Id == DM4Consts.ErrorUnknown)
        //    Response.Redirect(CommonVars.LoginPageRelUrl, true);

        try
        {

           


            if (GridView1.DataSource == null)
            {
               
            }

            //if (CommonVars.Ui != null)
            //    lblCurUser.Text = "User: " + CommonVars.Ui.Fullname;

            //set server description
            HttpCookie c = Request.Cookies[CommonVars.EndpointServerName];
            TimeSpan ts = CommonVars.Gi.StartupTime;

            lblCurServer.Text = string.Format("Current server: {0}, version {1}.<br />Server time: {2}, startup time: {3}."
                                              , c == null || string.IsNullOrEmpty(c.Value) ? "" : c.Value
                                              , CommonVars.Gi.Version
                                              , CommonVars.Gi.ServerTime.ToString("f", DateTimeFormatInfo.InvariantInfo)
                                              , string.Format("{0:D2} day(s) {1:D2}:{2:D2}:{3:D2}", ts.Days, ts.Hours, ts.Minutes, ts.Seconds));

            Label1.Text = string.Format("{0}; post back: {1}&nbsp;", DateTime.Now.ToString(), IsPostBack.ToString());

            RefreshAvailableUsers();
            FillLeftNavigatePanel();

        }
        catch (Exception ex)
        {
            CommonProc.SetLastError(ex.Message);
            Response.Redirect(CommonVars.LoginPageRelUrl, true);
        }
    }

    private void RefreshAvailableUsers()
    {
        //save selected user
        if (ddlUsers.SelectedItem != null
            && !string.IsNullOrEmpty(ddlUsers.SelectedItem.Value))
            CommonVars.SelectedUid = Convert.ToInt32(ddlUsers.SelectedItem.Value);
        else
            CommonVars.SelectedUid = DM4Consts.ErrorUnknown;

        //refresh CommonVars.Uil
        ddlUsers.Items.Clear();
        //if (CommonVars.Uil != null && CommonVars.Uil.Count > 0)
        //{
        //    pnlUsers.Visible = true;
        //    hrUsers.Visible = true;

        //    foreach (UserInfo ui in CommonVars.Uil)
        //        ddlUsers.Items.Add(new ListItem(ui.Fullname, ui.Id.ToString()));

        //    try
        //    {
        //        if (CommonVars.SelectedUid != DM4Consts.ErrorUnknown)
        //            ddlUsers.SelectedValue = CommonVars.SelectedUid.ToString();
        //    }
        //    catch (Exception)
        //    {
        //        CommonVars.SelectedUid = DM4Consts.ErrorUnknown;
        //        if (ddlUsers.Items.Count > 0)
        //        {
        //            ddlUsers.SelectedIndex = 0;
        //            CommonVars.SelectedUid = Convert.ToInt32(ddlUsers.SelectedValue);
        //        }
        //    }

        //    SetSelectedUserDescription();
        //}
        //else
        //{
        //    pnlUsers.Visible = false;
        //    hrUsers.Visible = false;
        //}
    }

    //private UserInfo GetUserInfoByUserId(int uid)
    //{
    //    if (CommonVars.Uil != null && CommonVars.Uil.Count > 0)
    //        return CommonVars.Uil.FirstOrDefault(uitmp => uitmp.Id == uid);

    //    return null;
    //}

    private void SetSelectedUserDescription()
    {
        //if (ddlUsers.Items.Count > 0 && !string.IsNullOrEmpty(ddlUsers.SelectedValue))
        //{
        //    UserInfo ui = GetUserInfoByUserId(Convert.ToInt32(ddlUsers.SelectedValue));
        //    if (ui != null)
        //    {
        //        lblLogin.Text = "Login: " + ui.Login;
        //        lblEmail.Text = "Email: " + (string.IsNullOrEmpty(ui.Email) ? "empty" : ui.Email);
        //        lblAccessLevel.Text = "AccessLevel: " + ui.AccessLevel;
        //        return;
        //    }
        //}

        lblLogin.Text = "";
        lblEmail.Text = "";
        lblAccessLevel.Text = "";
    }

    private void FillLeftNavigatePanel()
    {
        pnlPages.Controls.Add(new HyperLink { NavigateUrl = CommonVars.DefaultPageRelUrl, ToolTip = "Main page", Target = "_self", Text = "Main page", CssClass = "leftNavLink roundCorners" });
        pnlPages.Controls.Add(new HyperLink { NavigateUrl = CommonVars.LoginPageRelUrl, ToolTip = "La-la2", Target = "_self", Text = "Other Sessions", CssClass = "leftNavLink roundCorners" });
        pnlPages.Controls.Add(new HyperLink { NavigateUrl = CommonVars.LoginPageRelUrl, ToolTip = "La-la3", Target = "_self", Text = "Error Settings", CssClass = "leftNavLink roundCorners" });
        pnlPages.Controls.Add(new HyperLink { NavigateUrl = CommonVars.LoginPageRelUrl, ToolTip = "La-la4", Target = "_self", Text = "Log Settings", CssClass = "leftNavLink roundCorners" });
    }

    protected void RefreshUserListClick(object sender, ImageClickEventArgs e)
    {
        if (CommonProc.RefreshUserList())
            RefreshAvailableUsers();
    }

    protected void btnClick(object sender, EventArgs e)
    {
        panel1.Visible = panel2.Visible;
        panel2.Visible = !panel1.Visible;
        panel2_1.Visible = !panel1.Visible;
    }

    protected void trr(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    if (e.Row.RowIndex == 0)
        //        e.Row.Style.Add("height", "40px");
        //}
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //Set the edit index.
        GridView1.EditIndex = e.NewEditIndex;
        //Bind data to the GridView control.
        BindData();
    }

    private void BindData()
    {
        GridView1.DataSource = CommonVars.GroupInfods.Tables["tbl"];
        GridView1.DataBind();
    }

    protected void TaskGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //Reset the edit index.
        GridView1.EditIndex = -1;
        //Bind data to the GridView control.
        BindData();
    }

    protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //Retrieve the table from the session object.
        DataTable dt = (DataTable)CommonVars.GroupInfods.Tables["tbl"];

        //Update the values.
        GridViewRow row = GridView1.Rows[e.RowIndex];
        dt.Rows[row.DataItemIndex]["Disabled"] = ((CheckBox)(row.Cells[1].Controls[0])).Checked;
        dt.Rows[row.DataItemIndex]["Name"] = ((TextBox)(row.Cells[2].Controls[0])).Text;


        //Reset the edit index.
        GridView1.EditIndex = -1;

        //Bind data to the GridView control.
        BindData();
    }

    protected void TaskGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {

        GridView1.PageIndex = e.NewPageIndex;
        //Bind data to the GridView control.
        BindData();
    }
    protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
    {

    }
}